package com.aliyun.messagemgt.application.service.Impl;

import com.aliyun.messagemgt.application.service.MessageTemplateService;
import com.aliyun.messagemgt.common.errorcode.CommonErrorCode;
import com.aliyun.messagemgt.common.exceptions.BaseException;
import com.aliyun.messagemgt.domain.repository.MessageTemplateRepository;
import com.aliyun.messagemgt.domain.repository.MsgSourceRepository;
import com.aliyun.messagemgt.domain.repository.TemplateSmsSignRepository;
import com.aliyun.messagemgt.dto.MessageTemplate;
import com.aliyun.messagemgt.dto.TemplateSmsSign;
import com.aliyun.messagemgt.dto.query.MessageTemplateQuery;
import com.aliyun.messagemgt.dto.vo.DepVo;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author hzw
 * @Date 2020/12/16 11:26
 * @Version 1.0
 */
@Service
public class MessageTemplateServiceImpl implements MessageTemplateService {

    private static Logger logger = LoggerFactory.getLogger(MessageTemplateServiceImpl.class);

    @Autowired
    private MessageTemplateRepository messageTemplateRepository;

    @Autowired
    private TemplateSmsSignRepository templateSmsSignRepository;

    @Autowired
    private MsgSourceRepository msgSourceRepository;

    @Override
    public Integer templateModify(MessageTemplate add) {
        MessageTemplate template=new MessageTemplate();
        BeanUtils.copyProperties(add,template);
        return messageTemplateRepository.update(template);
    }

    @Override
    public void checkTemplate(MessageTemplate messageTemplate) {
        int flag = messageTemplateRepository.queryByCode(messageTemplate);
        if (flag > 0){
            throw new BaseException(CommonErrorCode.CODING_REPEAT);
        }
        int name = messageTemplateRepository.queryByTemplateName(messageTemplate);
        if (name > 0) {
            throw new BaseException(CommonErrorCode.COMMON_MESSAGE_TEMPLATE_NAME_ERROR);
        }
        int title = messageTemplateRepository.queryByTemplateTitle(messageTemplate);
        if (title > 0){
            throw new BaseException(CommonErrorCode.COMMON_TEMPLATE_TITLE_ERROR);
        }
    }

    @Override
    public PageInfo<MessageTemplate> queryList(MessageTemplateQuery query) {
        return messageTemplateRepository.queryListSign(query);
    }

    @Override
    public MessageTemplate templateDetail(MessageTemplateQuery query) {
        MessageTemplate messageTemplate = new MessageTemplate();
        messageTemplate.setTemplateId(query.getTemplateId());
        return messageTemplateRepository.queryByEntitySign(messageTemplate);
    }

    @Override
    public Integer templateDelete(MessageTemplateQuery query) {
        /*MessageTemplate templateQuery = new MessageTemplate();
        templateQuery.setTemplateId(query.getTemplateId());
        MessageTemplate messageTemplate = messageTemplateRepository.queryByEntity(templateQuery);
        //如果消息模板信息中包含消息源id，那么就判断消息源的状态，消息源为启用，才可以删除。
        Integer result;
        *//*if (messageTemplate.getMsgSourceId() == null) {
            logger.info("该消息模板未绑定消息源，删除消息模板");
            messageTemplate.setIsEnabled(MessageTemplateConstant.STATUS_UN_ACTIVE);
            result = messageTemplateRepository.update(messageTemplate);
        } else {
            logger.info("该消息模板已绑定消息源");
            String msgSourceId = messageTemplate.getMsgSourceId();
            MsgSource msgSource = msgSourceRepository.queryBySourceId(msgSourceId);
            if (msgSource == null) {
                logger.info("未查到绑定的消息源信息");
                messageTemplate.setIsEnabled(MessageTemplateConstant.STATUS_UN_ACTIVE);
                result = messageTemplateRepository.update(messageTemplate);
            } else {
                if (msgSource.getStateDelete() == 1) {
                    logger.info("消息源已删除，删除消息模板");
                    messageTemplate.setIsEnabled(MessageTemplateConstant.STATUS_UN_ACTIVE);
                    result = messageTemplateRepository.update(messageTemplate);
                } else {
                    logger.info("消息源使用中");
                    //这里没有判断消息源的有效期。以后有需求可以优化
                    throw new BaseException(CommonErrorCode.COMMON_MESSAGE_TEMPLATE_NAME_REPEAT_ERROR);
                }
            }
        }*//*
        // 删除模板签名关系
        if(messageTemplate != null && messageTemplate.getTemplateId() != null){
            List<TemplateSmsSign> templtIdSmsSign = templateSmsSignRepository.getTempltIdSmsSign(Math.toIntExact(messageTemplate.getTemplateId()));
            templtIdSmsSign.forEach(e -> templateSmsSignRepository.updateTempltIdSmsSign(e.getId()));
        }*/
        return null;
    }

    @Override
    public List<DepVo> deptList(MessageTemplateQuery query) {
        List<DepVo> depVoList = new ArrayList<>();
        List<MessageTemplate> pages = messageTemplateRepository.queryList(query);
        if (CollectionUtils.isNotEmpty(pages)) {
            DepVo depVo;
            for (MessageTemplate messageTemplate : pages) {
                depVo = new DepVo();
                if (StringUtils.isNotBlank(messageTemplate.getCreator())) {
                    depVo.setOwnerDept(messageTemplate.getCreator());
                    depVoList.add(depVo);
                }
            }
        }
        if (CollectionUtils.isNotEmpty(depVoList)) {
            return removeDuplicatesDep(depVoList);
        }
        return new ArrayList<>();
    }

    @Override
    public Integer saveTemplate(MessageTemplate messageTemplate) {

        return messageTemplateRepository.saveTemplate(messageTemplate);
    }

    @Override
    public Integer updateStatus(MessageTemplate messageTemplate) {
        return messageTemplateRepository.updateStatus(messageTemplate);
    }

    @Override
    public Integer isDelete(MessageTemplate messageTemplate) {
        return messageTemplateRepository.isDelete(messageTemplate);
    }

    @Override
    public Integer updateTemplate(MessageTemplate messageTemplate) {
        return messageTemplateRepository.updateTemplate(messageTemplate);
    }

    @Override
    public String queryByTemplateId(Long templateId) {
        return messageTemplateRepository.queryByTemplateId(templateId);
    }

    @Override
    public PageInfo<MessageTemplate> isEnabledList(MessageTemplateQuery query) {
        return messageTemplateRepository.isEnabledList(query);
    }

    /**
     *
     * @param templateId
     * @param smsSignId
     * @return
     */
    private Integer addTempltIdSmsSign(Long templateId, int smsSignId){
        List<TemplateSmsSign> templateSmsSigns = templateSmsSignRepository.getTempltIdSmsSign(Math.toIntExact(templateId));
        if(CollectionUtils.isNotEmpty(templateSmsSigns)){
            templateSmsSigns.forEach(e -> templateSmsSignRepository.updateTempltIdSmsSign(e.getId()));
        }
        TemplateSmsSign templateSmsSign = new TemplateSmsSign();
        templateSmsSign.setCreateTime(new Date());
        templateSmsSign.setUpdateTime(new Date());
        templateSmsSign.setTemplateId(templateId);
        templateSmsSign.setSmsSignId(smsSignId);
        return templateSmsSignRepository.insertTempltIdSmsSign(templateSmsSign);
    }

    /**
     * 创建消息模板id
     *
     * @return String
     */
    private String createTemplateId() {
        Long count = messageTemplateRepository.listCount();
        return "MT_" + (count + 1);
    }
    /**
     * 根据部门编码和部门名称去重
     *
     * @param depVoList 部门list
     * @return list
     */
    private List<DepVo> removeDuplicatesDep(List<DepVo> depVoList) {
        return depVoList.stream().collect(Collectors
                .collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(dep -> dep.getOwnerDept() + "," + dep.getOwnerDeptName()))), ArrayList::new));
    }

    public Long queryTemplateCount() {
        return messageTemplateRepository.listCount();
    }
}
